#!/bin/bash
# 自动化部署脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查依赖
check_dependencies() {
    log_info "检查部署依赖..."
    
    # 检查Docker
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装，请先安装Docker"
        exit 1
    fi
    log_success "Docker已安装: $(docker --version)"
    
    # 检查Docker Compose
    if ! command -v docker-compose &> /dev/null; then
        log_error "Docker Compose未安装，请先安装Docker Compose"
        exit 1
    fi
    log_success "Docker Compose已安装: $(docker-compose --version)"
    
    # 检查磁盘空间
    DISK_USAGE=$(df . | tail -1 | awk '{print $5}' | sed 's/%//')
    if [ "$DISK_USAGE" -gt 80 ]; then
        log_warning "磁盘使用率较高: ${DISK_USAGE}%"
    else
        log_success "磁盘空间充足: ${DISK_USAGE}%已使用"
    fi
}

# 创建必要目录
create_directories() {
    log_info "创建必要目录..."
    
    mkdir -p data output logs config reports
    chmod 755 data output logs config reports
    
    log_success "目录创建完成"
}

# 构建镜像
build_image() {
    log_info "构建Docker镜像..."
    
    # 清理旧镜像
    if docker images | grep -q mysql-to-kwdb-migrator; then
        log_info "清理旧镜像..."
        docker rmi mysql-to-kwdb-migrator_mysql-to-kwdb-migrator:latest || true
    fi
    
    # 构建新镜像
    docker-compose build --no-cache
    
    log_success "镜像构建完成"
}

# 运行测试
run_tests() {
    log_info "运行测试..."
    
    # 构建测试镜像
    docker-compose build mysql-to-kwdb-migrator
    
    # 运行单元测试
    docker-compose run --rm mysql-to-kwdb-migrator test
    
    log_success "测试通过"
}

# 部署服务
deploy_services() {
    log_info "部署服务..."
    
    # 停止现有服务
    docker-compose down || true
    
    # 启动服务
    docker-compose up -d
    
    # 等待服务启动
    log_info "等待服务启动..."
    sleep 10
    
    # 检查服务状态
    if docker-compose ps | grep -q "Up"; then
        log_success "服务部署成功"
    else
        log_error "服务部署失败"
        docker-compose logs
        exit 1
    fi
}

# 健康检查
health_check() {
    log_info "执行健康检查..."
    
    # 检查主服务
    if docker-compose exec -T mysql-to-kwdb-migrator ./scripts/health_check.sh; then
        log_success "主服务健康检查通过"
    else
        log_error "主服务健康检查失败"
        return 1
    fi
    
    # 检查API服务
    if curl -f http://localhost:8080/health &> /dev/null; then
        log_success "API服务健康检查通过"
    else
        log_warning "API服务健康检查失败（可能未启用）"
    fi
    
    log_success "健康检查完成"
}

# 显示部署信息
show_deployment_info() {
    log_info "部署信息:"
    echo "==========================================="
    echo "🚀 MySQL到KWDB迁移工具已成功部署"
    echo "==========================================="
    echo "📊 服务状态:"
    docker-compose ps
    echo ""
    echo "🌐 访问地址:"
    echo "  - API服务: http://localhost:8080"
    echo "  - 健康检查: http://localhost:8080/health"
    echo ""
    echo "📁 数据目录:"
    echo "  - 输入数据: ./data/"
    echo "  - 输出结果: ./output/"
    echo "  - 日志文件: ./logs/"
    echo "  - 报告文件: ./reports/"
    echo ""
    echo "🔧 常用命令:"
    echo "  - 查看日志: docker-compose logs -f"
    echo "  - 重启服务: docker-compose restart"
    echo "  - 停止服务: docker-compose down"
    echo "  - 运行迁移: docker-compose run --rm mysql-to-kwdb-migrator [options]"
    echo ""
    echo "📖 更多信息请查看 README.md"
    echo "==========================================="
}

# 主函数
main() {
    echo "🚀 MySQL到KWDB迁移工具自动化部署脚本"
    echo "========================================"
    
    # 解析命令行参数
    SKIP_TESTS=false
    SKIP_BUILD=false
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            --skip-tests)
                SKIP_TESTS=true
                shift
                ;;
            --skip-build)
                SKIP_BUILD=true
                shift
                ;;
            --help|-h)
                echo "用法: $0 [选项]"
                echo "选项:"
                echo "  --skip-tests    跳过测试"
                echo "  --skip-build    跳过镜像构建"
                echo "  --help, -h      显示帮助信息"
                exit 0
                ;;
            *)
                log_error "未知选项: $1"
                exit 1
                ;;
        esac
    done
    
    # 执行部署步骤
    check_dependencies
    create_directories
    
    if [ "$SKIP_BUILD" = false ]; then
        build_image
    fi
    
    if [ "$SKIP_TESTS" = false ]; then
        run_tests
    fi
    
    deploy_services
    health_check
    show_deployment_info
    
    log_success "🎉 部署完成！"
}

# 错误处理
trap 'log_error "部署过程中发生错误，请检查日志"; exit 1' ERR

# 运行主函数
main "$@"